package cn.gzjp.modules.woms.web.front;


import java.util.*;


import cn.gzjp.common.constant.Constants;
import cn.gzjp.common.web.AjaxResult;
import cn.gzjp.modules.woms.entity.EventProcess;
import cn.gzjp.modules.woms.service.EventProcessService;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.woms.entity.Event;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.EventService;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.gzjp.modules.wx.service.QyWxService;


/**
 * 企业号--故障安排应用（外场管理员）
 *
 */ 
@Controller
@RequestMapping(value = "${frontPath}/assigner")
@SessionAttributes(value = { "corpId", "agentId", "userId" })
public class AssignerController extends BaseController {
	
	@Autowired
	private WorkerService workerService;
	@Autowired
	private EventService eventService;
	@Autowired
	private QyWxService qyWxService;


	
	/**
	 * 未处理列表展示(未处理菜单)
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("undo")
	public String undo(@ModelAttribute("userId") String userId,Model model) {
	     Worker worker = workerService.get(userId);
	     Event event = new Event();
		 event.setStatus(Constants.EventStatus.create);//创建：后台导入新的
	     event.setInProjects(worker.getProjectsList());
	     List<Event> eventList = eventService.findList(event);

			Collections.sort(eventList, new Comparator<Event>(){
				public int compare(Event o1, Event o2) {
					if(o1.getLeftMinutes() > o2.getLeftMinutes()){
						return 1;
					}
					if(o1.getLeftMinutes() == o2.getLeftMinutes()){
						return 0;
					}
					return -1;
				}
			});

	     model.addAttribute("eventList",eventList);
		 return "modules/woms/front/assigner/undoList";
	}



	/**
	 * 已处理工单列表(已处理菜单)
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("done")
	public String done(@ModelAttribute("userId") String userId,Model model) {
		Worker worker = workerService.get(userId);
		Event event = new Event();
		event.setAssignerDone("y");
		event.setAssigner(worker);
		List<Event> eventList = eventService.findList(event);
		Collections.sort(eventList, new Comparator<Event>(){
			public int compare(Event o1, Event o2) {
				if(o1.getLeftMinutes() > o2.getLeftMinutes()){
					return 1;
				}
				if(o1.getLeftMinutes() == o2.getLeftMinutes()){
					return 0;
				}
				return -1;
			}
		});
		model.addAttribute("eventList",eventList);
		return "modules/woms/front/assigner/doneList";
	}

	/**
	 * 详细展示
	 * @param id  工单id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "event", method = RequestMethod.GET)
	public String event(String id,Model model){
		Event event = eventService.get(id);
		event.setAssigner(workerService.get(event.getCreaterId()));
		model.addAttribute("event", event);
		return "modules/woms/front/assigner/event";
	}

	/**
	 * 详细展示(就是那么恶心)
	 * @param id  工单id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "event2", method = RequestMethod.GET)
	public String event2(String id,Model model){
		Event event = eventService.get(id);
		event.setAssigner(workerService.get(event.getCreaterId()));
		model.addAttribute("event", event);
		return "modules/woms/front/assigner/event2";
	}


	/**
	 * 点击指派工程师按钮(进到指派工程师页面)
	 * @param id  工单id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "assignUI", method = RequestMethod.GET)
	public String assignUI(String id,Model model){
		Event event = eventService.get(id);
		if (event.getStatus().equals(Constants.EventStatus.create)) {//判断状态为：创建
			Worker search = new Worker();
			search.setRoles(Constants.WorkerRole.enginer);
			search.setProjectId(event.getOperationArea());
			List<Worker>  engineers  = workerService.findList(search);
			model.addAttribute("engineers", engineers);//专业工程师
			model.addAttribute("event", event);
			return "modules/woms/front/assigner/assign";//返回选人页面
		}
		model.addAttribute("event", event);
		return "modules/woms/front/assigner/event";//返回工单页面
	}

	/**
	 * 确认指派
	 * @param userId
	 * @param id   工单id
	 * @param engineerArr 选中的工程师
	 * @return
	 */
	@RequestMapping(value = "assign", method = RequestMethod.POST)
	@ResponseBody
	public String assign(@ModelAttribute("userId") String userId,  String id, @RequestParam(value = "engineerArr[]") String[] engineerArr) {
		if(engineerArr==null||engineerArr.length==0){
			AjaxResult ajaxResult = new AjaxResult();
			ajaxResult.setSuccess(false);
			ajaxResult.setMsg("请先选择工程师");
			return this.mapper.toJson(ajaxResult);
		}

		Event event = eventService.get(id);
		if(!Constants.EventStatus.create.equals(event.getStatus())){
			AjaxResult ajaxResult = new AjaxResult();
			ajaxResult.setSuccess(false);
			ajaxResult.setMsg("该工单已分派,请不要重复分派");
			return this.mapper.toJson(ajaxResult);
		}
		String content = eventService.assign(event,userId,engineerArr);
		for (int i = 0; i < engineerArr.length; i++) {
			//推送消息
			sendQyWxMessage(event, Constants.AgentId.enginer,"您有新的工单需要处理",event.getDeviceName()+"设备出现故障,请尽快处理",engineerArr[i]);
		}
		//推送消息 推送给分派员
		sendQyWxMessage(event, Constants.AgentId.assigner,"工单分派成功",content,event.getAssigner().getId());
		AjaxResult ajaxResult = new AjaxResult();
		ajaxResult.setSuccess(true);
		ajaxResult.setMsg("操作成功");
		return this.mapper.toJson(ajaxResult);


	}
	/**
	 * 用于页面js授权
	 * @param corpId
	 * @param url
	 * @return
	 */
	@RequestMapping(value = "jsApi", method = RequestMethod.POST)
	@ResponseBody
	public String jsApi(@ModelAttribute(value = "corpId") String corpId,
						@RequestParam("url") String url) {
		AjaxResult ajaxResult = new AjaxResult();
		WxJsapiSignature jspTitck;
		try {
			WxCpService wxCpService = this.qyWxService.getWxCpService(corpId,
					Constants.AgentId.assigner);
			jspTitck = wxCpService.createJsapiSignature(url);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("timestamp", jspTitck.getTimestamp());
			map.put("nonceStr", jspTitck.getNoncestr());
			map.put("signature", jspTitck.getSignature());
			ajaxResult.setSuccess(true);
			String json = mapper.toJson(map);
			ajaxResult.setMsg(json);
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
		}
		return mapper.toJson(ajaxResult);
	}

}
